<template>
  <div class="app-container">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcel from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
// import { formatExcelDate } from '@/utils/index'

export default {
  name: 'Import',
  components: { UploadExcel },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 1.读取excel表格转化为行和列的数据
      // 2.将数据安装接口文档进行格式转化将中文的健转化英文
      const data = this.transExcel(results)
      console.log(data)
      // 3.发送请求，实现数据的批量导入
      this.doAdd(data)
    },
    async doAdd(data) {
      try {
        const res = await importEmployee(data)
        console.log('导入excel', res)
        this.$router.back()
        this.$message.success(res.message)
      } catch (err) {
        console.log('导入excel', err)
        this.$message.error(err)
      }
    },
    transExcel(data) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      return data.map((ele) => {
        const arr = Object.keys(ele)
        const enobj = {}
        arr.forEach((item) => {
          enobj[mapInfo[item]] = ele[item]
        })
        return enobj
      })
    }
  }
}
</script>
